// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        // 获取数据库
        let msgArr = await db.collection("activityDB").get()
        // 发送信息
        for ( let msgData of msgArr.data ) {
            // 活动即将开始 但未开始
            let beginTime = msgData.beginTime
            let endTime = msgData.endTime
            let date = new Date()
            if (msgData.status == "finished") {
                continue
            }
            if ( date >= endTime ) {
                db.collection("activityDB").doc(msgData._id).update({
                    data: {
                        status: "finished"
                    }
                })
            }
            if ( date > beginTime )
                continue
            date = new Date(beginTime)
            let activityTime = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日"
            for ( let player in msgData.people ) {
                let applicant = msgData.people[player]
                if ( applicant.pushed == false ) {
                    db.collection("activityDB").doc(msgData._id).update({
                        data: {
                            [`people.${player}.pushed`]: true
                        }
                    })
                    await cloud.openapi.subscribeMessage.send({
                        touser: player,
                        templateId: "hzp3AiWK1_DZ8br2eL8XjUgoX2wxWTtYtTyD1a04E_o",
                        page: "pages/Activity/Activity",
                        data: {
                            thing1: {value:msgData.activity},
                            time2: {value: activityTime},
                            short_thing3: {value:"即将开始"},
                            short_thing8: {value:Object.keys(msgData.people).length},
                            thing6: {value:msgData.address}
                        }
                    })
                }
            }
        } 
        return msgArr
    }
    catch (err) {
        return err
    }
}